# encoding: utf-8
import logging
from logging.handlers import RotatingFileHandler

import redis

__author__ = 'binbin'
__date__ = '2018/10/13 0013 20:26'

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import configs
from flask_session import Session
from flask_wtf import CSRFProtect

db = SQLAlchemy()
redis_conn = None

def get_app(config_name):

    setupLogging(configs[config_name].LOGGIONG_LEVEL)

    app = Flask(__name__)

    app.config.from_object(configs[config_name])

    global db
    db.init_app(app)

    global redis_conn
    redis_conn = redis.StrictRedis(host=configs[config_name].REDIS_HOST,port=configs[config_name].REDIS_PORT)

    Session(app)

    CSRFProtect(app)

    return app


def setupLogging(levle):
    # 业务逻辑已开启就加载日志
    # 设置日志的记录等级
    logging.basicConfig(level=levle)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)
